<template>
  <el-cascader
    ref="cascader"
    v-model="currValue"
    v-bind="options"
    :options="areaList"
    :props="{
      value: 'id',
      label: 'text',
      children: 'children',
      leaf: 'isLeaf',
      checkStrictly: props.checkStrictly
    }"
    style="width: 100%"
  />
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import visual from "@/visual/js/visual";
import { useAreaStore } from "@/pinia/modules/area";

const props = defineProps({
  node: Object,
  compStyle: Object,
  compData: Object
});
const currNode = ref(props.node);
const areaStore = useAreaStore();
const currValue = ref(null);
const areaList = ref([]);

const options = computed(() => {
  const compStyle = props.compStyle || {};
  const options = {};
  visual.addIfNotNull(options, compStyle, 'size');
  visual.addIfNotNull(options, compStyle, 'placeholder');
  visual.addIfNotNull(options, compStyle, 'showAllLevels');
  visual.addIfNotNull(options, compStyle, 'required');
  visual.addIfNotNull(options, compStyle, 'filterable');
  visual.addIfNotNull(options, compStyle, 'clearable');
  visual.addIfNotNull(options, compStyle, 'disabled');
  return options;
});

const loadDataList = () => {
  areaStore.getAreaList().then(res => {
    areaList.value = res && res.length > 0 && res[0].children || [];
  });
};

const loadValue = async() => {
  const dataList = (await visual.loadData(props.compData, {}, {}, currNode.value)).data || [];
  currNode.value.compData.dataList = JSON.stringify(dataList);
  let defaultValue = dataList.length > 0 && dataList[0]['内容'] || '';
  if (defaultValue && defaultValue.startsWith('156,')) {
    defaultValue = defaultValue.substring(4);
  }
  currValue.value = defaultValue ? defaultValue.split(',') : [];
};

watch(() => props.compStyle, () => {
  if (!props.compData?.dataSourceType) {
    loadValue();
  }
}, {deep: true});

watch(() => props.compData?.refresh, () => {
  loadValue();
});

onMounted(() => {
  loadValue();
  loadDataList();
});
</script>